﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using FileManager.Files;
using System.ServiceModel;

namespace FileManager
{
    public partial class LoginPopup : ChildWindow
    {
        public bool IsAuthenticated = false;
        public string Server = "";
        public int UserID = 0;
        public string OOBPassword = "";

        public LoginPopup()
        {
            InitializeComponent();
        }

        #region CancelButton_Click
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        } 
        #endregion

        #region ResetLoginPopup
        public void ResetLoginPopup()
        {
            lblStatus.Text = "";
        } 
        #endregion

        #region btnLogin_Click
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            WebServiceSoapClient objWebServiceSoapClient = new WebServiceSoapClient();
            EndpointAddress MyEndpointAddress = new EndpointAddress(txtServer.Text + @"/webservice/Webservice.asmx");
            objWebServiceSoapClient.Endpoint.Address = MyEndpointAddress;

            lblStatus.Text = "Authenticating...";

            objWebServiceSoapClient.GetOOBPasswordCompleted += new EventHandler<GetOOBPasswordCompletedEventArgs>(objWebServiceSoapClient_GetOOBPasswordCompleted);
            objWebServiceSoapClient.GetOOBPasswordAsync(0, 0, txtUserName.Text, txtPassword.Password);
        }

        void objWebServiceSoapClient_GetOOBPasswordCompleted(object sender, GetOOBPasswordCompletedEventArgs e)
        {
            try
            {
                if (e.Result == "")
                {
                    lblStatus.Text = "Authentication Failed";
                }
                else
                {
                    lblStatus.Text = "Authenticated!";
                    btnLogin.Visibility = Visibility.Collapsed;

                    int intSeparator = e.Result.IndexOf("_");
                    UserID = Convert.ToInt32(e.Result.Substring(0, intSeparator));
                    intSeparator++;
                    OOBPassword = e.Result.Substring(intSeparator, (e.Result.Length - intSeparator));
                    Server = txtServer.Text + @"/webservice/Webservice.asmx";
                    IsAuthenticated = true;
                }
            }
            catch (Exception)
            {
                lblStatus.Text = "Authentication Failed";
            }
        } 
        #endregion
    }
}

